package com.youlu.campus.service.item.Impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.CaInfo;
import com.youlu.campus.entity.ItemStockConfig;
import com.youlu.campus.entity.VO.req.ItemStockConfigVO;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.item.ItemStockConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ItemStockConfigServiceImpl implements ItemStockConfigService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityService activityService;

    @Override
    public Page<ItemStockConfig> list(ItemStockConfigVO request) {
        Query query = new Query();
        ActivityInfo activityInfo = activityService.findOne(request.getActivityId());
        if (StringUtils.isNotBlank(request.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(request.getActivityId()));
        }
        if (StringUtils.isNotBlank(request.getCaInfoId())) {
            query.addCriteria(Criteria.where("caInfoId").is(request.getCaInfoId()));
        }
        if (StringUtils.isNotBlank(request.getCaMeterialConfigId())) {
            query.addCriteria(Criteria.where("caMeterialConfigId").is(request.getCaMeterialConfigId()));
        }
        Date date = new Date();
        query.addCriteria(Criteria.where("deleted").ne(true));
        Long count = mongoTemplate.count(query, ItemStockConfig.class);
        if (count < 1L) {
            log.error(":>>> 活动的商品配货列表为空:{}", request.getActivityId());
            Query queryCa = new Query().addCriteria(Criteria.where("activityId").is(request.getActivityId()));
            List<CaInfo> caInfos = mongoTemplate.find(queryCa, CaInfo.class);
            if (!CollectionUtils.isEmpty(caInfos)) {
                for (CaInfo caInfo : caInfos) {
                    ItemStockConfig itemStockConfig = new ItemStockConfig();
                    itemStockConfig.setActivityId(request.getActivityId());
                    itemStockConfig.setActivityName(activityInfo.getName());
                    itemStockConfig.setCaInfoId(caInfo.getId());
                    itemStockConfig.setCaInfoName(caInfo.getName());
                    itemStockConfig.setStock(caInfo.getNum());
                    itemStockConfig.setOperatorConfigedStock(caInfo.getNum());
                    itemStockConfig.setCreatedTime(date);
                    itemStockConfig.setCaInfo(caInfo);
                    mongoTemplate.insert(itemStockConfig);
                }
            }
        }
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ItemStockConfig> activityInfos = mongoTemplate.find(query.with(pageRequest), ItemStockConfig.class);
        log.info(":>>> 商品库存列表:{}", activityInfos == null ? 0 : activityInfos.size());
        Long finalCount = count;
        return PageableExecutionUtils.getPage(activityInfos, pageRequest, () -> finalCount);
    }

    @Override
    public boolean update(ItemStockConfig req, String optUserLoginName, String optUserRealName) {
        log.info(":>>> 开始修改库存配置:{},{}", JSON.toJSONString(req), optUserRealName);
        if (Objects.isNull(req) || StringUtils.isBlank(req.getId())) {
            log.error(":>>> 商品库存配置错误");
            throw new BusinessException("商品库存配置错误");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        ItemStockConfig existConfig = mongoTemplate.findOne(query, ItemStockConfig.class);
        if (CollectionUtils.isEmpty(existConfig.getOptLogs())) {
            existConfig.setOptLogs(new ArrayList<>());
        }
        Update update = new Update();
        boolean updated = false;
        if (Objects.nonNull(req.getStock()) && !req.getStock().equals(existConfig.getReqStock())) {
            update.set("stock", req.getStock());
            existConfig.getOptLogs().add(new Date() + "," + optUserLoginName + ",将库存修改为:" + req.getStock());
            updated = true;
        }
        if (Objects.nonNull(req.getMissStock()) && !req.getMissStock().equals(existConfig.getMissStock())) {
            update.set("missStock", req.getMissStock());
            updated = true;
        }
        if (Objects.nonNull(req.getOccupiedStock()) && !req.getOccupiedStock().equals(existConfig.getOccupiedStock())) {
            update.set("occupiedStock", req.getOccupiedStock());
            updated = true;
        }
        if (Objects.nonNull(req.getReqStock()) && !req.getReqStock().equals(existConfig.getReqStock())) {
            update.set("reqStock", req.getReqStock());
            updated = true;
        }
        if (!CollectionUtils.isEmpty(existConfig.getOptLogs())) {
            update.set("optLogs", existConfig.getOptLogs());
        }
        if (Objects.nonNull(req.getOperatorConfigedStock()) && !req.getOperatorConfigedStock().equals(existConfig.getOperatorConfigedStock())) {
            update.set("operatorConfigedStock", req.getOperatorConfigedStock());
            updated = true;
        }
        if (updated) {
            update.set("updatedTime", new Date());
        }
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ItemStockConfig.class);
        log.info(":>>> 更新商品库存配置:{},结果:{}", req.getId(), updateResult.getModifiedCount() > 0 ? true : false);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public boolean create(ItemStockConfig req) {
        req.setCreatedTime(new Date());
        req.setId(null);
        mongoTemplate.insert(req);
        return true;
    }

    @Override
    public ItemStockConfig findByCaInfoId(String caInfoId) {
        log.info(":>>> 开始查找商品库存配置:{}", caInfoId);
        if (StringUtils.isBlank(caInfoId)) {
            log.error(":>>> 商品ID为空:{}", caInfoId);
            new BusinessException("商品ID为空");
        }
        Query query = new Query().addCriteria(Criteria.where("caInfoId").is(caInfoId));
        ItemStockConfig config = mongoTemplate.findOne(query, ItemStockConfig.class);
        log.info(":>>>  商品:{} 库存配置信息为:{}", caInfoId, JSON.toJSONString(config));
        return config;
    }

    @Override
    public ItemStockConfig findOne(String id) {
        log.info(":>>> 开始查找商品库存配置:{}", id);
        if (StringUtils.isBlank(id)) {
            log.error(":>>> 商品ID 为空", id);
            throw new BusinessException("商品ID 为空");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        ItemStockConfig config = mongoTemplate.findOne(query, ItemStockConfig.class);
        log.info(":>>> 商品库存配置:{} 信息:{}",id,JSON.toJSONString(config));
        return config;
    }
}
